<template>
  <el-dialog :visible.sync="dialogFormVisible" width="70%" :append-to-body="true" :close-on-click-modal="false" center>
    <template slot="title">
      <span class="add-main-tital">
        <h4>物资分发</h4>
      </span>
    </template>
    <div class="add-container">

      <div class="add-main">

        <div class="add-main-list">
          <div class="list-button-group">
            <div class="button-item">
              <el-button type="primary" icon="el-icon-s-home">
                整体选择库房
              </el-button>
            </div>

            <div class="button-item">
              <el-button type="primary" icon="el-icon-share" @click="insertEvent">
                拆分
              </el-button>
            </div>
            <!-- <div class="button-item">
              <el-button type="success" icon="el-icon-s-check">
                分发确认
              </el-button>
            </div> -->
          </div>
          <div class="table-list">
            <ux-grid border show-overflow ref="plxTable" keep-source :height="tabheight" :highlightCurrentRow="false"
              widthResize :rules="rules" :validConfig="{ autoPos: true }" @selection-change="selectChange"
              :edit-config="{ trigger: 'click', mode: 'cell' }">
              <ux-table-column type="checkbox" width="50" />
              <ux-table-column type="index" title="序号" width="50"></ux-table-column>
              <ux-table-column field="wuzimc" title="物资名称"></ux-table-column>
              <ux-table-column field="guigexh" width="80" title="规格型号">
              </ux-table-column>
              <ux-table-column field="jiliangdw" width="80" title="计量单位"></ux-table-column>
              <ux-table-column field="wuzisl" width="150" title="调拨入库数量" :edit-render="{ autofocus: '.el-input__inner' }">
                <template v-slot:edit="scope">
                  <el-input v-model.trim="scope.row.wuzisl" type="number" :min="1" placeholder="请输入数量"
                    @keyup.native="scope.row.wuzisl = oninput(scope.row.wuzisl, scope.row)" />
                </template>
              </ux-table-column>
              <ux-table-column field="kufangid" title="分发库房" width="140" :edit-render="{ autofocus: '.el-input__inner' }">
                <template v-slot:edit="scope">
                  <el-select v-model="scope.row.kufangid">
                    <el-option v-for="item in kfList" :key="item.value" :label="item.mingcheng"
                      :value="item.id"></el-option>
                  </el-select>
                </template>
                <template v-slot="{ row }">{{ KufangListOne(row.kufangid) }}</template>
              </ux-table-column>

              <ux-table-column field="picih" title="批次号"></ux-table-column>

              <ux-table-column show-overflow-tooltip field="danjia" title="单价"
                :edit-render="{ autofocus: '.el-input__inner' }">
                <template v-slot:edit="scope">
                  <el-input v-model.trim="scope.row.danjia" placeholder="请输入单价" />
                </template>
              </ux-table-column>

              <ux-table-column show-overflow-tooltip field="shengchanrq" title="生产日期"></ux-table-column>
              <ux-table-column show-overflow-tooltip field="shengchancj" title="生产厂家">
              </ux-table-column>


            </ux-grid>

          </div>
        </div>
      </div>

    </div>

    <span slot="footer" class="dialog-footer">
      <el-button size="medium" type="primary" icon="el-icon-s-check" @click="save">
        确定
      </el-button>
      <el-button size="medium" icon="el-icon-delete" @click="close">
        取 消
      </el-button>

    </span>
  </el-dialog>
</template>
<script>
import Upload from '@/components/Upload/upload'
import { insertRukudByDbd } from '@/api/warehousing'
export default {
  name: 'page2Fenfa',
  components: { Upload },
  data() {
    return {
      show: true,
      ruleForm: {
        rkdh: '',
        wzmc: '',
        wzqf: '',
        rkzt: '',
        rklx: '',
        datalist: [],
      },
      // rules: {
      //   rkdh: [{ required: true, message: '请输入入库单号', trigger: 'blur' }],
      // },
      rules: {
        wuzisl: [{ required: true, message: '请输入数量', trigger: 'blur' },],
        kufangid: [{ required: true, message: '请选择库房', trigger: 'blur' }],
      },
      tabheight: 500,
      importShow: false,
      kfList: [],
      dialogFormVisible: false,
      selectrow: [],
    }
  },
  created() { },
  async mounted() {
    let kfList = await this.$util.getKf()
    this.kfList = kfList.rows

  },
  computed: {
    mxListLS: function () {
      let str = this.ruleForm.rukudbdmxList.concat(this.$refs.plxTable.getRecordset())
      return str;
    },
  },
  methods: {
    showEdit(row) {
      this.ruleForm = Object.assign({}, row)
      this.dialogFormVisible = true
      this.ruleForm.rukudbdmxList.forEach(item => {
        item.danjia = item.cankaojg//里面没有单价，但是有参与价格
        item.biaozhundwsl = item.wuzisl
      });
      this.$nextTick(() => {
        this.$refs.plxTable.reloadData(this.ruleForm.rukudbdmxList)
      })
    },
    close() {
      //  this.$refs['form'].resetFields()
      //  this.form = this.$options.data().form
      this.selectrow = []
      this.dialogFormVisible = false
    },
    save() {
      this.$refs.plxTable.validate(true).then(async (data) => {
        if (data) {
          // 有错误
        }
        else {
          this.ruleForm.insertRukuDbd = this.$refs.plxTable.getTableData().fullData
          let ruleForm2 = {}
          ruleForm2.rukutzdid = this.ruleForm.id;
          ruleForm2.rukudMapList = this.$refs.plxTable.getTableData().fullData
          delete ruleForm2.rukudMapList.forEach(item => {
            delete item.cankaojg
            delete item.zhengshibmm
            delete item.shijirkwzsl
            delete item._XID
            delete item.id
            delete item.rukudbdid
          });
          const msg = await insertRukudByDbd('?rukutzdid=' + this.ruleForm.id, ruleForm2.rukudMapList)
          this.$message({
            message: '分发成功',
            type: 'success',
          })
          // 验证通过
          this.$emit('fetch-data')
          this.close()
        }
      })
    },
    goBack() {
      this.$parent.addshow = false
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          alert('submit!')
        } else {
          return false
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    selectChange(e) {
      this.selectrow = e
    },
    // 新增插入行
    async insertEvent() {
      if (this.selectrow.length !== 1) {
        this.$message({
          message: '请选择一条进行拆分，不要多选',
          type: 'error',
        })
        return false
      }
      let record = Object.assign({}, this.selectrow[0])
      record.maxwuzisl = record.wuzisl
      record.wuzisl = 0
      record.kufangid = null;
      // let record = {}
      // 加入行, 表示加入行的row对象，row为空则插入第一行，为-1插入最后一行
      let { row: newRow } = await this.$refs.plxTable.insertRow(record)
      // 激活单元格编辑
      // await this.$refs.plxTable.setActiveRow(newRow)
    },
    delwzDetail() {
      this.$refs.plxTable.remove(this.$refs.plxTable.getCheckboxRecords())
    },
    uploadSuccess() {
      this.importShow = false
    },
    oninput(num, row) {
      let maxvalue = 0
      let newArr = this.mxListLS.filter(item => row._XID == item._XID)
      newArr.forEach((item) => { maxvalue += Number(item.wuzisl) })
      let n = num.replace(/[^\d.]/g, '')
      if (maxvalue > row.biaozhundwsl) {
        this.$message.error('当前行最大值不能大于总和')
        n = 0
        return
      }
      return n
    },

    KufangListOne(id) {
      if (id) {
        let datarow = this.kfList.filter(item => item.id == id);
        return datarow[0].mingcheng;
      }
      return null
    },

  },
}
</script>
<style lang="scss" scoped>
.add-container {

  width: 100%;
  height: 100%;
  z-index: 1000;
  background-color: #f6f8f9;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  overflow: hidden;

  .add-top {


    ::v-deep .el-page-header__title {
      font-size: 16px !important;
    }
  }

  .add-main {
    flex: 1;
    font-weight: bold;
    display: flex;
    flex-direction: column;
    overflow: auto;

    .add-main-top {
      padding: .2rem;
      background: #fff;
      border-radius: .05rem;

      .add-main-tital {
        font-size: .18rem;
        border-left: .10rem solid rgb(121, 189, 255);
        padding-left: .10rem;

        p {
          margin: 0;
        }
      }

      .search-gropu-item {
        margin-top: .20rem;
        width: 90%;
        display: flex;
        // label {
        //   white-space: nowrap;
        //   line-height: 32px;
        //   margin-right: 10px;
        // }
      }

      .el-select {
        width: 100%;
      }
    }

    .add-main-list {
      flex: 1;
      background: #fff;
      box-sizing: border-box;

      .list-button-group {
        display: flex;
        flex-direction: row;
        padding: 15px;

        .button-item {
          padding: 0px 10px;
        }

        .button-item:first-child,
        &:last-child {
          padding: 0px 10px 0 0;
        }
      }
    }

    .el-button {
      font-size: .14rem !important;
    }

    ::v-deep {
      .elx-table--header-wrapper {
        background-color: rgb(233, 243, 255);
      }

      .elx-table {
        font-size: 0.14rem !important;
      }

      .elx-body--column {
        height: .48rem !important;
        line-height: .24rem;
      }

      .elx-header--column {
        background-image: none !important;
        height: .48rem !important;
      }

      .el-date-editor.el-input,
      .el-date-editor.el-input--inner {
        width: 100% !important;
      }

      .el-form-item--small.el-form-item {
        margin-bottom: 0px;
        margin-top: 18px;
      }
    }

    .submit-button {
      margin-top: 20px;
      display: flex;
      justify-content: center;
    }
  }
}
</style>